package com.nsi.service.Impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nsi.common.Const;
import com.nsi.util.RedisUtils;
import com.nsi.common.ResponseCode;
import com.nsi.common.ServerResponse;
import com.nsi.controller.visualization.pojo.SchoolItem;
import com.nsi.controller.visualization.pojo.SchoolVisualization;
import com.nsi.dao.CoordinateMapper;
import com.nsi.dao.SchoolCertificationMapper;
import com.nsi.dao.SchoolMapper;
import com.nsi.exception.NsiOperationException;
import com.nsi.pojo.Coordinate;
import com.nsi.pojo.School;
import com.nsi.pojo.SchoolCertification;
import com.nsi.service.ISchoolService;
import com.nsi.util.DateTimeUtil;
import com.nsi.vo.SchoolVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: Luo Zhen
 * @date: 2018/11/2 17:08
 * @description:
 */
@Service
public class SchoolServiceImpl implements ISchoolService {

    private static final String VISUAL_MODEL = "visualSchoolModel";
    private static final long EXPIRE_TIME = 864000000;

    @Autowired
    private SchoolMapper schoolMapper;
    @Autowired
    private CoordinateMapper coordinateMapper;
    @Autowired
    private SchoolCertificationMapper schoolCertificationMapper;

    @Override
    public ServerResponse addSchoolInfo(School school, SchoolCertification certification) {
        if (StringUtils.isBlank(school.getSchoolName())) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        int rowCount;
        try {
            school.setLoadTime(DateTimeUtil.dateToStr(new Date()));
            rowCount = schoolMapper.insert(school);
            if (rowCount <= 0) {
                throw new NsiOperationException("添加学校信息失败");
            }
        } catch (Exception e) {
            throw new NsiOperationException("addSchool error:" + e.getMessage());
        }
        int schoolId = school.getId();
        if (StringUtils.isNotBlank(certification.getCertificateAuthority()) || StringUtils.isNotBlank(certification.getStudentEvaluation()) ||
                StringUtils.isNotBlank(certification.getThirdOrganizations()) || StringUtils.isNotBlank(certification.getCourseAuthority())) {
            certification.setSchoolId(schoolId);
            certification.setAnyCertification(String.valueOf(ResponseCode.YES_AUTHENTICATION.getCode()));
        } else {
            certification.setSchoolId(schoolId);
            certification.setAnyCertification(String.valueOf(ResponseCode.NO_AUTHENTICATION.getCode()));
        }
        try {
            rowCount = schoolCertificationMapper.insert(certification);
            if (rowCount <= 0) {
                throw new NsiOperationException("添加学校权威认证信息失败");
            }
        } catch (Exception e) {
            throw new NsiOperationException("addSchoolCertification error:" + e.getMessage());
        }
        return ServerResponse.createBySuccessMessage("添加学校信息成功");

    }

    /**
     * 展示学校库广告位
     *
     * @param keyword
     * @return
     */
    @Override
    public ServerResponse showSchoolBoards(String keyword) {
        if (keyword == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        List<School> schoolList = schoolMapper.getBoardsByNameAndId(keyword);
        return ServerResponse.createBySuccess(schoolList);
    }

    /**
     * 高级搜索
     *
     * @param area
     * @param fondTime
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ServerResponse<PageInfo> searchPower(String[] properties, String[] area, String[] system, String[] course, String fondTime, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<String> listProperties = null;
        List<String> listAreas = null;
        List<String> listSystem = null;
        List<String> listCourse = null;
        if (properties != null) {
            listProperties = Arrays.asList(properties);
        }
        if (area != null) {
            listAreas = Arrays.asList(area);
        }
        if (system != null) {
            listSystem = Arrays.asList(system);
        }
        if (course != null) {
            listCourse = Arrays.asList(course);
        }
        List<School> schools = schoolMapper.searchPower(listProperties, listAreas, listSystem, listCourse, fondTime);
        PageInfo pageInfo = new PageInfo(schools);
        return ServerResponse.createBySuccess(pageInfo);
    }


    @Override
    public ServerResponse<PageInfo> searchPowerList(
            String[] area, String[] system, String[] properties,
            String[] authority, String[] evaluation,
            String[] organization, String[] course, int pageNum, int pageSize) {

        PageHelper.startPage(pageNum, pageSize);
        List<String> listAreas = null;
        List<String> listSystem = null;
        List<String> listProperties = null;
        List<String> listAuthority = null;
        List<String> listEvaluation = null;
        List<String> listOrganization = null;
        List<String> listCourse = null;
        if (area != null) {
            listAreas = Arrays.asList(area);
        }
        if (system != null) {
            listSystem = Arrays.asList(system);
        }
        if (properties != null) {
            listProperties = Arrays.asList(properties);
        }
        if (authority != null) {
            listAuthority = Arrays.asList(authority);
        }
        if (evaluation != null) {
            listEvaluation = Arrays.asList(evaluation);
        }
        if (organization != null) {
            listOrganization = Arrays.asList(organization);
        }
        if (course != null) {
            listCourse = Arrays.asList(course);
        }
        List<School> schoolList = schoolMapper.searchPowerList(listAreas, listSystem, listProperties, listAuthority, listEvaluation, listOrganization, listCourse);
        PageInfo pageInfo = new PageInfo(schoolList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse getSchoolItemList() {
        List<School> schoolList = schoolMapper.getList("", String.valueOf(ResponseCode.PASS.getCode()));
        List<SchoolItem> lists = new ArrayList<>();
        for (School school : schoolList) {
            SchoolItem item = assembleSchoolItem(school);
            lists.add(item);
        }
        return ServerResponse.createBySuccess(lists);
    }

    private SchoolItem assembleSchoolItem(School school) {
        SchoolItem item = new SchoolItem();
        item.setId(school.getId());
        item.setSchoolName(school.getSchoolName());
        item.setAreas(school.getAreas());
        item.setAreas02(school.getAreas02());
        item.setAreas03(school.getAreas03());
        item.setSchoolProperties(school.getSchoolProperties());
        item.setTuition01(school.getTuition01());
        item.setTuition02(school.getTuition02());
        item.setTuition03(school.getTuition03());
        item.setTuition04(school.getTuition04());
        item.setCourse(school.getCourse());
        item.setFoundedTime(school.getFoundedTime());
        return item;

    }

    /**
     * 搜索功能
     *
     * @param searchKey
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ServerResponse searchList(String searchKey, String orderBy, int pageNum, int pageSize, String verifyCode) {
        PageHelper.startPage(pageNum, pageSize);
        //排序处理
        if (StringUtils.isNotBlank(orderBy)) {
            if (Const.SchoolListOrderBy.SCHOOL_ASC_DESC.contains(orderBy)) {
                String[] orderByArray = orderBy.split("-");
                PageHelper.orderBy(orderByArray[0] + " " + orderByArray[1]);
            }
        }

        List<School> schoolList = schoolMapper.getList(StringUtils.isBlank(searchKey) ? "" : searchKey, verifyCode);
        PageInfo pageInfo = new PageInfo(schoolList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    /**
     * 只能搜索学校名
     *
     * @param searchKey
     * @return
     */
    @Override
    public ServerResponse getSchoolName(String searchKey) {
        String stringBuffer = null;
        if (StringUtils.isNotBlank(searchKey)) {
            stringBuffer = new StringBuffer().append("%").append(searchKey).append("%").toString();
        }
        List<String> schoolName = schoolMapper.getSchoolName(stringBuffer);
        return ServerResponse.createBySuccess(schoolName);
    }

    /**
     * 根据Id获取详情
     *
     * @param schoolId
     * @return
     */
    @Override
    public ServerResponse getDetail(Integer schoolId) {
        if (schoolId == null) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        School school = schoolMapper.selectByPrimaryKey(schoolId);
        return ServerResponse.createBySuccess(school);
    }

    @Override
    public ServerResponse checkValidedByName(String schoolName) {
        if (StringUtils.isBlank(schoolName)) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        int rowCount = schoolMapper.checkBySchoolName(schoolName);
        if (rowCount > 0) {
            return ServerResponse.createByErrorMessage("学校名字已存在");
        }
        return ServerResponse.createBySuccessMessage("验证成功");

    }


    /**
     * 可视化(添加学校经纬度)
     *
     * @param coordinate
     * @return
     */
    @Override
    public ServerResponse saveOn(Coordinate coordinate) {
        if (coordinate.getSchoolId() == null) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        int rowCount = coordinateMapper.selectCountBySchoolId(coordinate.getSchoolId());
        if (rowCount > 0) {
            return ServerResponse.createByErrorMessage("该记录已存在");
        }
        Coordinate currentCoor = new Coordinate();
        currentCoor.setSchoolId(coordinate.getSchoolId());
        currentCoor.setLongitude(coordinate.getLongitude());
        currentCoor.setLatitude(coordinate.getLatitude());
        currentCoor.setCreateTime(new Date());

        rowCount = coordinateMapper.insert(currentCoor);
        if (rowCount > 0) {
            return ServerResponse.createBySuccessMessage("添加成功");
        }
        return ServerResponse.createByErrorMessage("添加失败");
    }

    /**
     * 可视化(返回学校制定字段)
     *
     * @return
     */
    @Override
    public ServerResponse getVisualizationSchoolList() {
        String visualStr = RedisUtils.searchRedis(VISUAL_MODEL);
        List<SchoolVisualization> lists = null;
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = null;
        if (visualStr != null) {
            // redis数据还原成List
            JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, SchoolVisualization.class);
            try {
                lists = mapper.readValue(visualStr, javaType);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ServerResponse.createBySuccess(lists);
        } else {
            List<School> schoolList = schoolMapper.getList("", String.valueOf(ResponseCode.PASS.getCode()));
            lists = new ArrayList<>();
            for (School school : schoolList) {
                SchoolVisualization visualization = assemble(school);
                lists.add(visualization);
            }
            try {
                jsonStr = mapper.writeValueAsString(lists);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            RedisUtils.expireSet(VISUAL_MODEL, EXPIRE_TIME, jsonStr);
            return ServerResponse.createBySuccess(lists);
        }
    }

    /**
     * 组合高级模型
     *
     * @param school
     * @return
     */
    private SchoolVisualization assemble(School school) {
        SchoolVisualization visualization = new SchoolVisualization();
        visualization.setId(school.getId());
        visualization.setSchoolName(school.getSchoolName());
        visualization.setSchoolProperties(school.getSchoolProperties());
        visualization.setSchoolSystem(school.getSchoolSystem());
        visualization.setSchoolLogo(school.getSchoolLogo());
        visualization.setCourse(school.getCourse());
        visualization.setAreas(school.getAreas());
        visualization.setAreas02(school.getAreas02());
        visualization.setAreas03(school.getAreas03());
        visualization.setTuition01(school.getTuition01());
        visualization.setTuition02(school.getTuition02());
        visualization.setTuition03(school.getTuition03());
        visualization.setTuition04(school.getTuition04());

        Coordinate coordinate = coordinateMapper.selectBySchoolId(school.getId());
        if (coordinate != null) {
            visualization.setLongitude(coordinate.getLongitude());
            visualization.setLatitude(coordinate.getLatitude());
        }
        return visualization;
    }

    @Override
    public ServerResponse getSchoolList(String searchKey, int pageNum, int pageSize, String verifyCode) {
        PageHelper.startPage(pageNum, pageSize);
        List<School> schoolList = schoolMapper.getList(searchKey, verifyCode);
        List<SchoolVo> schoolVoList = new ArrayList();
        for (School schoolItem : schoolList) {
            SchoolVo schoolVo = assembleSchoolVo(schoolItem);
            schoolVoList.add(schoolVo);
        }
        PageInfo pageInfo = new PageInfo(schoolList);
        pageInfo.setList(schoolVoList);
        return ServerResponse.createBySuccess("返回成功", (int) pageInfo.getTotal(), pageInfo.getList());
    }


    @Override
    public ServerResponse removeSchoolList(Integer schoolId) throws NsiOperationException {
        if (schoolId == null) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        int rowCount;
        try {
            rowCount = schoolMapper.deleteByPrimaryKey(schoolId);
            if (rowCount <= 0) {
                throw new NsiOperationException("删除school失败");
            }
        } catch (Exception e) {
            throw new NsiOperationException("remove school error:" + e.getMessage());
        }
        try {
            rowCount = schoolCertificationMapper.selectAll(schoolId);
            if (rowCount >= 0) {
                schoolCertificationMapper.deleteBySchoolId(schoolId);
            }
        } catch (Exception e) {
            throw new NsiOperationException("remove schoolCertification error:" + e.getMessage());
        }
        return ServerResponse.createBySuccessMessage("删除学校信息成功");
    }

    @Override
    public ServerResponse modifySchoolCategory(School school, SchoolCertification schoolCertification) throws NsiOperationException {
        if (school.getId() == null || StringUtils.isBlank(school.getSchoolName())) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        int rowCount;
        try {
            school.setLoadTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            schoolMapper.updateByPrimaryKeySelective(school);
        } catch (Exception e) {
            throw new NsiOperationException("modify school error:" + e.getMessage());
        }
        rowCount = schoolCertificationMapper.selectAll(school.getId());
        if (rowCount <= 0) {
            SchoolCertification currentSchool = new SchoolCertification();
            currentSchool.setSchoolId(school.getId());
            currentSchool.setCertificateAuthority(this.isEmpty(schoolCertification.getCertificateAuthority()) ? "0" : schoolCertification.getCertificateAuthority());
            currentSchool.setStudentEvaluation(this.isEmpty(schoolCertification.getStudentEvaluation()) ? "0" : schoolCertification.getStudentEvaluation());
            currentSchool.setThirdOrganizations(this.isEmpty(schoolCertification.getThirdOrganizations()) ? "0" : schoolCertification.getThirdOrganizations());
            currentSchool.setCourseAuthority(this.isEmpty(schoolCertification.getCourseAuthority()) ? "0" : schoolCertification.getCourseAuthority());
            currentSchool.setAnyCertification(String.valueOf(ResponseCode.YES_AUTHENTICATION.getCode()));

            schoolCertificationMapper.insert(currentSchool);
        } else {
            if (StringUtils.isNotBlank(schoolCertification.getCourseAuthority()) || StringUtils.isNotBlank(schoolCertification.getThirdOrganizations()) ||
                    StringUtils.isNotBlank(schoolCertification.getStudentEvaluation()) || StringUtils.isNotBlank(schoolCertification.getCertificateAuthority())) {
                SchoolCertification currentSchool = new SchoolCertification();
                currentSchool.setSchoolId(school.getId());
                currentSchool.setCertificateAuthority(schoolCertification.getCertificateAuthority());
                currentSchool.setStudentEvaluation(schoolCertification.getStudentEvaluation());
                currentSchool.setThirdOrganizations(schoolCertification.getThirdOrganizations());
                currentSchool.setCourseAuthority(schoolCertification.getCourseAuthority());
                currentSchool.setAnyCertification(String.valueOf(ResponseCode.YES_AUTHENTICATION.getCode()));
                try {
                    rowCount = schoolCertificationMapper.modifyBySchoolId(currentSchool, school.getId());
                    if (rowCount <= 0) {
                        throw new NsiOperationException("修改学校认证信息失败");
                    }
                } catch (Exception e) {
                    throw new NsiOperationException("modify schoolCertification error:" + e.getMessage());
                }
            }
        }
        return ServerResponse.createBySuccessMessage("修改学校信息成功");
    }

    private boolean isEmpty(String str) {
        if (StringUtils.isEmpty(str)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public ServerResponse getSchoolNum(String option) {
        Map<String, Object> resultMap = new HashMap<>();
        for (int i = 0; i < Const.CHINA_AREAS.length; i++) {
            int count = schoolMapper.getEchartSchoolNum(Const.CHINA_AREAS[i], option);
            resultMap.put(Const.CHINA_AREAS[i], count);
        }
        return ServerResponse.createBySuccess(resultMap);
    }

    @Override
    public ServerResponse getTimeList(String beginTime, String endTime) {
        List<School> timeList = schoolMapper.getTimeList(beginTime, endTime);
        return ServerResponse.createBySuccess(timeList);
    }


    /**
     * 组合SchoolVo高级模型
     *
     * @param school
     * @return
     */
    private SchoolVo assembleSchoolVo(School school) {
        SchoolVo schoolVo = new SchoolVo();
        schoolVo.setId(school.getId());
        schoolVo.setSchoolName(school.getSchoolName());
        schoolVo.setSchoolEnglishname(school.getSchoolEnglishname());
        schoolVo.setSchoolProperties(school.getSchoolProperties());
        schoolVo.setAreas(school.getAreas());
        schoolVo.setAreas02(school.getAreas02());
        schoolVo.setAreas03(school.getAreas03());
        schoolVo.setFoundedTime(school.getFoundedTime());
        schoolVo.setOperationstate(school.getOperationstate());
        schoolVo.setSchoolSystem(school.getSchoolSystem());
        schoolVo.setTuition01(school.getTuition01());
        schoolVo.setTuition02(school.getTuition02());
        schoolVo.setTuition03(school.getTuition03());
        schoolVo.setTuition04(school.getTuition04());
        schoolVo.setTuitionhigh(school.getTuitionhigh());
        schoolVo.setWebsite(school.getWebsite());
        schoolVo.setTelephone(school.getTelephone());
        schoolVo.setInterCourseFoundedTime(school.getInterCourseFoundedTime());
        schoolVo.setCourse(school.getCourse());
        schoolVo.setAuthentication(school.getAuthentication());
        schoolVo.setCourseEvaluation(school.getCourseEvaluation());
        schoolVo.setStudentNumAll(school.getStudentNumAll());
        schoolVo.setStudentNum01(school.getStudentNum01());
        schoolVo.setStudentNum02(school.getStudentNum02());
        schoolVo.setStudentNum03(school.getStudentNum03());
        schoolVo.setStudentNum04(school.getStudentNum04());
        schoolVo.setStudentCapacity(school.getStudentCapacity());
        schoolVo.setGraduatedStuNum(school.getGraduatedStuNum());
        schoolVo.setStuDominantNationality(school.getStuDominantNationality());
        schoolVo.setStuYearInvestment(school.getStuYearInvestment());
        schoolVo.setClubNum(school.getClubNum());
        schoolVo.setPresidentCountry(school.getPresidentCountry());
        schoolVo.setStaffNum(school.getStaffNum());
        schoolVo.setTeacherNum(school.getTeacherNum());
        schoolVo.setForeignTeacherNum(school.getForeignTeacherNum());
        schoolVo.setTeacherYearInvestment(school.getTeacherYearInvestment());
        schoolVo.setTeacherRetention(school.getTeacherRetention());
        schoolVo.setTeacherSalary(school.getTeacherSalary());
        schoolVo.setTeacherStuRatio(school.getTeacherStuRatio());
        schoolVo.setCoveredArea(school.getCoveredArea());
        schoolVo.setBuiltArea(school.getBuiltArea());
        schoolVo.setHardware(school.getHardware());
        schoolVo.setInvestment(school.getInvestment());
        schoolVo.setRemark(school.getRemark());
        schoolVo.setRecentModifier(school.getRecentModifier());
        schoolVo.setLoadPeople(school.getLoadPeople());
        schoolVo.setLoadTime(school.getLoadTime());
        schoolVo.setUn09(school.getUn09());
        schoolVo.setUn10(school.getUn10());
        schoolVo.setSchoolLogo(school.getSchoolLogo());
        schoolVo.setSchoolShow(school.getSchoolShow());
        schoolVo.setImg02(school.getImg02());
        schoolVo.setImg03(school.getImg03());
        schoolVo.setImg04(school.getImg04());
        schoolVo.setImg05(school.getImg05());
        schoolVo.setBatchinputSign(school.getBatchinputSign());
        schoolVo.setVerifysign(school.getVerifysign());
        schoolVo.setEvaluate(school.getEvaluate());

        // 根据schoolId 查询学校审核库 不为空的赋值
        SchoolCertification certification = schoolCertificationMapper.selectSchoolBySchoolId(school.getId());
        if (certification != null) {
            schoolVo.setCertificateAuthority(certification.getCertificateAuthority());
            schoolVo.setStudentEvaluation(certification.getStudentEvaluation());
            schoolVo.setThirdOrganizations(certification.getThirdOrganizations());
            schoolVo.setCourseAuthority(certification.getCourseAuthority());
            schoolVo.setAnyCertification(certification.getAnyCertification());
        }
        return schoolVo;
    }
}
